const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
  mode: "production",
  devtool: false,
  entry: "./src/main.js",
  output: {
    filename: "js/[name]_[chunkhash:5].js",
    path: path.resolve(__dirname, "dist"),
    clean: true,
    chunkFilename: "js/[name]_[chunkhash:5].js", // 为小的chunk进行命名
  },
  target: "web",
  optimization: {
    // 设置生成chunkId的算法
    // chunkIds: "named", // development默认为 named
    chunkIds: "deterministic", // deterministic：确定的数字，webpack4为natural，自动增加
    splitChunks: {
      chunks: "all", // 默认为async 只针对异步分包
      maxSize: 20000, // 当一个包大于指定的大小时，继续进行拆分
      minSize: 10, // 将包查封成不小于minSize的包
      cacheGroups: {
        utils: {
          test: /utils/,
          filename: "js/[name]_utils.js",
        },
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          filename: "js/[name]_vendors.js",
        },
      },
    },
    minimizer: [
      new TerserPlugin({
        extractComments: false, // 注释的单独提取
        parallel: true,
        terserOptions: {
          // https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions
        },
      }),
    ],
  },
  devServer: {
    static: ["public", "content"], // 静态资源目录，默认为public
    liveReload: false, // 编译失败后是否重新刷新整个页面
    host: "0.0.0.0",
    port: "3000",
    open: true,
    compress: true, // 打包的文件是否压缩
    proxy: [
      {
        context: ["/api", "/auth"], // 需要代理的路径
        target: "http://123.207.32.32:9002", // 目标服务器
        changeOrigin: true, // 修改请求头中的 host
        pathRewrite: {
          "^/api": "", // 重写路径（可选）
        },
      },
    ],
    historyApiFallback: true, // 页面404时是否重定向到首页
  },
  resolve: {
    extensions: [".js", ".json", ".jsx", ".vue", ".ts"],
  },
  module: {
    rules: [
      {
        test: /\.m?jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
      {
        test: /\.ts$/,
        use: ["babel-loader"],
        // use: "babel-loader",
      },
    ],
  },
  plugins: [
    new TerserPlugin(),
    new HtmlWebpackPlugin({
      template: "./index.html",
    }),
  ],
};
